package com.ktmall.ktmalluijava.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author ZhouShuang
 * @version 17
 * @Title 阿里云工具类
 * @date 2025/5/9 下午1:23
 */
@Component
public class OssUtil {

    @Value("${oss.endpoint}")
    private String endpoint ; //杭州服务器endpoint
    @Value("${oss.accessKey}")
    private String accessKeyId ; //自己的accessKeyId
    @Value("${oss.secretKey}")
    private String accessKeySecret; //自己的accessKeySecret
    @Value("${oss.bucketName}")
    private String bucketName; //写自己的bucket的名称

    /**
     * 实现上传图片到oss
     * @param multipartFile
     * @return
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        //获取上传文件的输入流
        InputStream inputStream = multipartFile.getInputStream();
        //重新命名，避免文件覆盖
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"))+multipartFile.getOriginalFilename();
        //上传文件到oss
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName,fileName,inputStream);

        //返回图片的oss网络地址
        return "https://"+bucketName+"."+endpoint+"/"+fileName;
    }
}
